//
//  WKWebViewController.swift
//  swift各类控件集锦
//
//  Created by iosdev1 on 2017/5/8.
//  Copyright © 2017年 zyy. All rights reserved.
//

import UIKit
import WebKit

class WKWebViewController: ZyBaseViewController,UINavigationControllerDelegate {

    var mainView:ZyBaseWebView? = nil
    var url:String = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.init(patternImage: UIImage.init(named: "girl")!)
        
        weak var weakSelf = self
        // 创建配置
        let config = WKWebViewConfiguration.init()
        // 创建UserContentController（提供JavaScript向webView发送消息的方法）
        let userContent = WKUserContentController.init()
            // 添加消息处理，注意：self指代的对象需要遵守WKScriptMessageHandler协议，结束时需要移除
//        userContent.add(self as! WKScriptMessageHandler, name: "nativeMethod")
//        userContent.removeScriptMessageHandler(forName: "nativeMethod")
//        userContent.removeAllUserScripts()
//
           // 将UserConttentController设置到配置文件
        config.allowsInlineMediaPlayback = true
        config.processPool = WKProcessPool.init()
        config.userContentController = userContent
        
        let preferences = WKPreferences.init()
        preferences.javaScriptEnabled = true

        // 默认是不能通过JS自动打开窗口的，必须通过用户交互才能打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        config.preferences = preferences
        
//        let userScript = WKUserScript.init(source: "source", injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: true)
//
        //    要区分打开H5是在本地APP还是在手机浏览器，前端伙伴说需要配合修改默认的 UserAgent,以便区分。
        //    修改全局UserAgent值（这里是在原有基础上拼接自定义的字符串）
          // 获取 iOS 默认的 UserAgent，可以很巧妙地创建一个空的UIWebView来获取：
//        let userAgent = UIWebView.init().stringByEvaluatingJavaScript(from: "navigator.userAgent")
//        echo(data: "\(String(describing: userAgent))")
//        let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
//        let customUserAgent = "ios/jkbs/" + (version as! String)
//        
//        UserDefaults.standard.register(defaults: ["UserAgent":customUserAgent])
//        UserDefaults.standard.synchronize()
        
         // 高端的自定义配置创建WKWebView
        mainView = ZyBaseWebView.init(frame: CGRect(x:0, y:0, width:WIDTH_SCREEN, height:HEIGHT_SCREEN), configuration: config)
        self.view.addSubview(mainView!)
        (mainView!).GetTitleClosure = {
            (data)in
            //            self.title = data//修改下面tabbar的title和上面self.navigationController的title
            //            self.navigationController?.title = data//修改下面tabbar的title
            self.navigationItem.title = data//修改上面self.navigationController的title
        }
        
        mainView?.evaluateJavaScript("navigator.userAgent", completionHandler: { (result, error) in
            echo(data: "\(String(describing: result))")
             //    判断网址类型
//            self.url = "http://www.jianshu.com/u/761d2ff3dcf1"
            self.url = "https://www.baidu.com/"//加载百度网址不能修改useragent,其他的网址可以
            if (weakSelf?.url.contains("indexlocal"))! {
                 //        本地html
                (weakSelf?.mainView!)?.YgLoadLocationUrl(url: (weakSelf?.url)!)
            }else{
                (weakSelf?.mainView!)?.YgLoadNoneParaUrl(url: (weakSelf?.url)!)
            }            
        })
        
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
